package com.blindBox.front.handler.loginHandler.loginHandlerImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blindBox.front.commonResult.MsgBackToFront;
import com.blindBox.front.dao_pojo.User;
import com.blindBox.front.exception.UserNotAutowiredException;
import com.blindBox.front.handler.loginHandler.AbstractLoginHandler;
import com.blindBox.front.handler.tokenHandler.TokenHandler;
import com.blindBox.front.handler.verify.Verify;
import com.blindBox.front.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


//处理账户和密码登录
@Component("loginByAccountHandler")
public class LoginByAccountHandler implements AbstractLoginHandler
{
    private volatile User user=new User();
    //校验账户登录类
    @Resource(name="uAccountVerify")
    private Verify userLoginByAccountVerify;
    @Autowired
    private TokenHandler tokenHandler;
    @Autowired
    private UserService userService;
    //注入属性
    public synchronized LoginByAccountHandler autoWiredUser(String uname,String upwd)
    {
        user.setUname(uname);
        user.setUpwd(upwd);
        return this;
    }
    //注入属性
    public synchronized LoginByAccountHandler autoWiredUser(User user)
    {
         this.user=user;
        return this;
    }
    //检验是否登录成功
    private synchronized MsgBackToFront verifyLogin() throws UserNotAutowiredException
    {
        //还没有注入属性
        if(user==null)
        {
           throw new UserNotAutowiredException();
        }
        //检验当前用户的登录正确性
        return (MsgBackToFront)userLoginByAccountVerify.verify(user);
    }

    @Override
    public  synchronized MsgBackToFront login()
    {
        try {
            //如果登录成功
            if(verifyLogin().getStatus()==MsgBackToFront.HANDLE_SUCCESS)
            {
                //将账号和密码进行加密，返回给前端加密后的token
                String token = tokenHandler.encryptionUnameAndUpwd(user);
                return new MsgBackToFront(token,MsgBackToFront.HANDLE_SUCCESS);
            }
             return verifyLogin();
        } catch (UserNotAutowiredException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //如果出现异常
        return new MsgBackToFront(null,MsgBackToFront.EXCEPTION_ERROR);
    }

     //获取当前用户的id
    public synchronized MsgBackToFront getUInfo(String uname)
    {
        User u = userService.getOne(new QueryWrapper<User>().eq("uname", uname));
        if(u==null)
            return new MsgBackToFront(null,MsgBackToFront.DATABASE_ERROR);
        return new MsgBackToFront(u,MsgBackToFront.HANDLE_SUCCESS);
    }
}
